package org.jsola.hr.service.impl;

import com.alibaba.excel.EasyExcel;
import jodd.util.StringUtil;
import org.jsola.admin.dto.HeaderFieldsAddDTO;
import org.jsola.admin.query.HeaderFieldsQuery;
import org.jsola.admin.vo.HeaderFieldsVO;
import org.jsola.common.DateKit8;
import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.common.ExcelKit;
import org.jsola.hr.constant.FieldType;
import org.jsola.hr.constant.FormGroupModuleCode;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.ITreatmentDisposeEventDAO;
import org.jsola.hr.dto.*;
import org.jsola.hr.entity.*;
import org.jsola.hr.provider.IAdminProviderService;
import org.jsola.hr.query.FormGroupFieldQuery;
import org.jsola.hr.query.TreatmentDisposeEventExportQuery;
import org.jsola.hr.query.TreatmentDisposeEventQuery;
import org.jsola.hr.service.*;
import org.jsola.hr.service.excel.TreatmentDisposeEventListener;
import org.jsola.hr.vo.*;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import static org.jsola.hr.constant.FormGroupModuleCode.PROCESS_CHILD;

/**
 * 待遇处理事件
 *
 * @author zhr
 */
@Service("hrTreatmentDisposeEventServiceImpl")
public class TreatmentDisposeEventServiceImpl implements ITreatmentDisposeEventService {

    @Autowired
    private ITreatmentDisposeEventDAO treatmentDisposeEventDAO;

    @Autowired
    private IFormGroupFieldValueService formGroupFieldValueService;

    @Lazy
    @Autowired
    private ITreatmentDisposeTemplateService treatmentDisposeTemplateService;

    @Autowired
    private IFormGroupService formGroupService;

    @Autowired
    private IFormGroupFieldService formGroupFieldService;

    @Autowired
    private IAdminProviderService adminProviderService;

    @Autowired
    private IEmpInfoService empInfoService;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public TreatmentDisposeEventVO save(TreatmentDisposeEventAddDTO treatmentDisposeEventAddDTO, TokenUser tokenUser) {
        List<String> necessaryList = Arrays.asList("姓名", "身份证号", "手机号", "性别");
        // 转DO
        TreatmentDisposeEventDO treatmentDisposeEventDO = treatmentDisposeEventAddDTO.to(TreatmentDisposeEventDO.class);
        treatmentDisposeEventDO.setIsFinish(false);
        // 保存
        treatmentDisposeEventDO = save(treatmentDisposeEventDO, tokenUser.getSiteId(), tokenUser.getUserId());
        List<FormGroupFieldValueAddDTO> fieldValueList = treatmentDisposeEventAddDTO.getFieldValueList();
        if (!CollectionUtils.isEmpty(fieldValueList)) {
            // 保存字段值的subjectId为事件的Id
            for (FormGroupFieldValueAddDTO formGroupFieldValue : fieldValueList) {
                if (necessaryList.contains(formGroupFieldValue.getFieldName()) &&
                        StringUtil.isEmpty(formGroupFieldValue.getContent())) {
                    throw new ParamException(formGroupFieldValue.getFieldName() + "不能为空");
                }
                formGroupFieldValue.setSubjectId(treatmentDisposeEventDO.getId());
            }
            formGroupFieldValueService.batchSave(fieldValueList, tokenUser);
        }
        return treatmentDisposeEventDO.to(TreatmentDisposeEventVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(TreatmentDisposeEventUpdateDTO updateDTO, TokenUser tokenUser) {
        //转DO
        TreatmentDisposeEventDO treatmentDisposeEventDO = updateDTO.to(TreatmentDisposeEventDO.class);
        // 因为 updateByIdSelective 只更新非null值 这里改成空串
        if (StringUtil.isEmpty(treatmentDisposeEventDO.getWorkCity())) {
            treatmentDisposeEventDO.setWorkCity("");
        }
        List<FormGroupFieldValueUpdateDTO> fieldList = updateDTO.getFieldValueList();
        List<String> necessaryList = Arrays.asList("姓名", "身份证号", "手机号", "性别");
        for (FormGroupFieldValueUpdateDTO update : fieldList) {
            if (necessaryList.contains(update.getFieldName()) && StringUtil.isEmpty(update.getContent())) {
                throw new ParamException(update.getFieldName() + "不能为空");
            }
            FormGroupFieldValueDO updateFieldValue = update.to(FormGroupFieldValueDO.class);
            updateFieldValue.setSubjectId(updateDTO.getId());
            if (StringUtil.isEmpty(updateFieldValue.getContent())) {
                updateFieldValue.setContent("");
            }
            formGroupFieldValueService.updateByIdSelective(updateFieldValue);
        }
        //根据主键更新，只更新非null值
        return updateByIdSelective(treatmentDisposeEventDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... treatmentDisposeEventIds) {
        List<String> eventIdList = Arrays.asList(treatmentDisposeEventIds);
        List<FormGroupFieldValueDO> fieldValueList = formGroupFieldValueService
                .selectBySubjectIdList(eventIdList, tokenUser);
        List<Long> fieldValueIdList = fieldValueList.stream()
                .map(FormGroupFieldValueDO::getId).collect(Collectors.toList());
        // 删除事件时同步删除事件下的字段值
        Long[] eventIdArray = new Long[fieldValueIdList.size()];
        formGroupFieldValueService.logicalDeleteByIds(tokenUser.getSiteId(),
                tokenUser.getUserId(), (Object[]) fieldValueIdList.toArray(eventIdArray));
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(),
                (Object[]) treatmentDisposeEventIds);
    }

    @Override
    public TreatmentDisposeEventVO selectById(String treatmentDisposeEventId, String siteId) {
        TreatmentDisposeEventDO treatmentDisposeEventDO = selectDOById(treatmentDisposeEventId, siteId);
        if (treatmentDisposeEventDO == null) {
            return null;
        }
        return treatmentDisposeEventDO.to(TreatmentDisposeEventVO.class);
    }

    @Override
    public List<TreatmentDisposeEventListVO> select(TreatmentDisposeEventQuery treatmentDisposeEventQuery, String siteId) {
        List<TreatmentDisposeEventDO> treatmentDisposeEventDOList = selectDO(treatmentDisposeEventQuery, siteId);
        if (CollectionUtils.isEmpty(treatmentDisposeEventDOList)) {
            return treatmentDisposeEventDOList == null ? null : new ArrayList<>();
        }
        return treatmentDisposeEventDOList.stream()
                .map(treatmentDisposeEventDO -> treatmentDisposeEventDO.to(TreatmentDisposeEventListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(TreatmentDisposeEventQuery treatmentDisposeEventQuery, String siteId) {
        Example example = buildExample(treatmentDisposeEventQuery, siteId);
        return treatmentDisposeEventDAO.selectCountByExample(example);
    }

    @Override
    public Page<TreatmentDisposeEventListVO> selectPage(TreatmentDisposeEventQuery treatmentDisposeEventQuery, String siteId) {
        Example example = buildExample(treatmentDisposeEventQuery, siteId);
        if (treatmentDisposeEventQuery.getIsFinish()) {
            example.orderBy("finishDate").desc();
        } else {
            example.orderBy("isPrecedence").desc().orderBy("gmtCreate").desc();
        }
        Page<TreatmentDisposeEventDO> page = treatmentDisposeEventDAO.selectPageByExample(example,
                treatmentDisposeEventQuery.getPageNo(),
                treatmentDisposeEventQuery.getPageSize());
        return page.to(TreatmentDisposeEventListVO.class);
    }

    @Override
    public TreatmentDisposeEventDO selectDOById(String treatmentDisposeEventId, String siteId) {
        return listById(treatmentDisposeEventId, siteId);
    }

    @Override
    public List<TreatmentDisposeEventDO> selectDO(TreatmentDisposeEventQuery treatmentDisposeEventQuery, String siteId) {
        Example example = buildExample(treatmentDisposeEventQuery, siteId);
        return treatmentDisposeEventDAO.selectByExample(example);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void finishOrUnfinishedEvent(String eventId, Boolean status, TokenUser tokenUser) {
        if (status) {
            TreatmentDisposeEventDO treatmentDisposeEvent = new TreatmentDisposeEventDO();
            treatmentDisposeEvent.setId(eventId);
            treatmentDisposeEvent.setIsFinish(true);
            treatmentDisposeEvent.setFinishDate(new Date());
            this.updateByIdSelective(treatmentDisposeEvent, tokenUser.getSiteId(), tokenUser.getUserId());
        } else {
            treatmentDisposeEventDAO.setNullFinishDate(eventId);
        }
    }

    @Override
    public TreatmentDisposeEventVO selectEventInfoById(String eventId, TokenUser tokenUser) {
        TreatmentDisposeEventDO event = this.selectDOById(eventId, tokenUser.getSiteId());
        if (ObjectUtils.isEmpty(event)) {
            throw new ParamException("事件不存在或已被删除");
        }
        TreatmentDisposeTemplateVO template = treatmentDisposeTemplateService.selectById(event.getTemplateId(), tokenUser.getSiteId());
        TreatmentDisposeEventVO result = event.to(TreatmentDisposeEventVO.class);
        result.setTemplateName(template.getTemplateName());
        List<FormGroupVO> formGroupList = treatmentDisposeTemplateService
                .selectFormGroupByTemplateId(template.getId(), eventId, tokenUser);
        result.setFormGroupTree(formGroupList);
        result.setCurrentWorkflow(StringUtil.isEmpty(result.getCurrentWorkflow()) ? "" : result.getCurrentWorkflow());
        result.setWorkCity(StringUtil.isEmpty(result.getWorkCity()) ? "" : result.getWorkCity());
        return result;
    }

    @Override
    public List<TreatmentDisposeEventDO> selectNotFinishEventByTemplateId(String templateId, TokenUser tokenUser) {
        Example example = new Example(TreatmentDisposeEventDO.class);
        example.and()
                .andEqualTo("templateId", templateId)
                .andEqualTo("isFinish", false)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        return treatmentDisposeEventDAO.selectByExample(example);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void bachUpdateFinish(List<String> eventIdList) {
        Example example = new Example(TreatmentDisposeEventDO.class);
        example.and().andIn("id", eventIdList);
        TreatmentDisposeEventDO treatmentDisposeEvent = new TreatmentDisposeEventDO();
        treatmentDisposeEvent.setIsFinish(true);
        treatmentDisposeEventDAO.updateByExampleSelective(treatmentDisposeEvent, example);
    }

    @Override
    public ImportExcelResultListVO<Map<String, String>> importEvent(File file, String templateId, TokenUser tokenUser) {
        ImportExcelResultListVO<Map<String, String>> result = new ImportExcelResultListVO<>();
        TreatmentDisposeEventListener listener = new TreatmentDisposeEventListener();


        List<FormGroupVO> formGroupList = formGroupService
                .selectBySubjectIdAndFormType(templateId, FormGroupModuleCode.DYCL, null, tokenUser);
        // 查询模板下的表单及字段
        List<String> formGroupIdList = formGroupList.stream()
                .map(formGroup -> formGroup.getId() + "").collect(Collectors.toList());
        List<FormGroupFieldDO> formGroupFieldList = formGroupFieldService
                .selectBySubjectIdList(formGroupIdList, "site");
        listener.setTemplateFieldMap(formGroupFieldList.stream()
                .collect(Collectors.toMap(FormGroupFieldDO::getFieldName, v -> v)));
        listener.setFieldList(formGroupFieldList.stream()
                .map(FormGroupFieldDO::getFieldName).collect(Collectors.toList()));
        // 导入的时候会过滤文件类型的字段,这里给他也过滤一下
        List<FormGroupFieldDO> filterList = formGroupFieldList.stream()
                .filter(field -> !FieldType.IMAGE_UPLOAD.getValue().equals(field.getFieldType()))
                .collect(Collectors.toList());
        List<String> moduleCodeList = filterList.stream()
                .map(FormGroupFieldDO::getModuleCode).distinct().collect(Collectors.toList());
        int headRowNumber = 3;
        if (!moduleCodeList.contains(PROCESS_CHILD)) {
            listener.setHeadIndex(1);
            headRowNumber = 2;
        }
        listener.setTokenUser(tokenUser);
        listener.setTemplateId(templateId);
        EasyExcel.read(file, listener).sheet().headRowNumber(headRowNumber).doRead();
        result.setAllCount(listener.getAllCount());
        result.setErrorCount(listener.getErrorCount());
        result.setSuccessCount(listener.getAllCount() - listener.getErrorCount());
        // 组装表头
        Map<Integer, String> headMap = listener.getHeadMap();
        List<String> headList = new ArrayList<>();
        headList.add("错误信息");
        for (Integer headIndex : headMap.keySet()) {
            headList.add(headMap.get(headIndex));
        }
        result.setHeadList(headList);
        result.setErrorList(listener.getErrorList());
        return result;
    }

    @Override
    public String errorListExport(ImportExcelResultListVO<Map<String, String>> errorInfo) {
        List<String> errorHeadList = errorInfo.getHeadList();
        List<Map<String, String>> errorErrorList = errorInfo.getErrorList();
        ParamException.notEmpty(errorHeadList, "表头不能为空");
        ParamException.notEmpty(errorErrorList, "无数据可导出");
        List<List<String>> headList = new ArrayList<>();
        for (String head : errorHeadList) {
            List<String> oneData = new ArrayList<>();
            oneData.add(head);
            headList.add(oneData);
        }
        List<List<String>> dataList = new ArrayList<>();
        for (Map<String, String> errorData : errorErrorList) {
            List<String> oneData = new ArrayList<>();
            for (String head : errorHeadList) {
                oneData.add(errorData.get(head));
            }
            dataList.add(oneData);
        }
        return ExcelKit.exportExcelNotTemplate2("错误数据导出", dataList, headList, "错误数据");
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void saveImport(List<Map<String, String>> saveList, Map<String, FormGroupFieldDO> templateFieldMap,
                           String templateId, TokenUser tokenUser) {
        if (CollectionUtils.isEmpty(saveList)) {
            return;
        }
        TreatmentDisposeTemplateDO template = treatmentDisposeTemplateService
                .selectDOById(templateId, tokenUser.getSiteId());
        List<TreatmentDisposeEventDO> eventList = new ArrayList<>();
        List<FormGroupFieldValueAddDTO> fieldValueList = new ArrayList<>();
        List<Long> fileValueIdList = new ArrayList<>();
        // 因为模板里面把附件类型的字段剔除了或者他手动给删除了Excel里面的某些字段
        // 导致导入的时候没有  如果没有保存的话在事件详情里面展示不出来  所以这里需要把这些字段搞出来 批量保存一下
        Map<String, String> map = saveList.get(0);
        for (String name : templateFieldMap.keySet()) {
            FormGroupFieldDO formGroupField = templateFieldMap.get(name);
            if (FieldType.IMAGE_UPLOAD.getValue().equals(formGroupField.getFieldType())) {
                fileValueIdList.add(formGroupField.getId());
                continue;
            }
            if (!map.containsKey(name)) {
                fileValueIdList.add(formGroupField.getId());
            }
        }
        for (Map<String, String> dataMap : saveList) {
            String eventId = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            // 接单时间
            String takeOrdersDate = null;
            // 接单客服Id
            String takeOrdersUserId = dataMap.get("接单客服Id");
            // 接单客服
            String takeOrdersUserName = null;
            // 所属用工单位
            String companyName = null;
            // 员工姓名
            String empName = null;
            // 员工身份证号
            String empIdCard = null;
            // 员工Id
            String empId = dataMap.get("员工Id");
            // 所属用工单位Id
            String companyId = dataMap.get("所属用工单位Id");
            // 工作地点
            String workCity = null;
            for (String head : dataMap.keySet()) {
                String value = dataMap.get(head);
                FormGroupFieldDO formGroupField = templateFieldMap.get(head);
                if ("接单时间".equals(head)) {
                    takeOrdersDate = value;
                    continue;
                }
                if ("接单客服".equals(head)) {
                    takeOrdersUserName = value;
                    continue;
                }
                if ("所属用工单位".equals(head)) {
                    companyName = value;
                    continue;
                }
                if ("工作地点".equals(head)) {
                    workCity = value;
                }
                if ("姓名".equals(head)) {
                    empName = value;
                }
                if ("身份证号".equals(head)) {
                    empIdCard = value;
                }
                if (!ObjectUtils.isEmpty(formGroupField)) {
                    FormGroupFieldValueAddDTO fieldValue = new FormGroupFieldValueAddDTO();
                    fieldValue.setFieldId(formGroupField.getId());
                    fieldValue.setContent(value);
                    fieldValue.setSubjectId(eventId);
                    fieldValue.setSubjectType(FormGroupModuleCode.DYCL);
                    fieldValueList.add(fieldValue);
                }
            }
            TreatmentDisposeEventDO event = new TreatmentDisposeEventDO();
            event.setTemplateId(templateId);
            event.setEventType(template.getEventType());
            event.setIsFinish(false);
            event.setWorkCity(workCity);
            event.setTakeOrdersUserId(takeOrdersUserId);
            event.setTakeOrdersUserName(takeOrdersUserName);
            event.setTakeOrdersDate(DateKit8.parseDate(takeOrdersDate));
            event.setIsPrecedence(false);
            event.setEmpId(empId);
            event.setEmpName(empName);
            event.setEmpIdCard(empIdCard);
            event.setCompanyId(companyId);
            event.setCompanyName(companyName);
            event.preInsert(tokenUser.getUserId());
            event.setSiteId(tokenUser.getSiteId());
            event.setId(eventId);
            eventList.add(event);
            if (!CollectionUtils.isEmpty(fileValueIdList)) {
                for (Long fileValueId : fileValueIdList) {
                    FormGroupFieldValueAddDTO fileValue = new FormGroupFieldValueAddDTO();
                    fileValue.setFieldId(fileValueId);
                    fileValue.setSubjectType(FormGroupModuleCode.DYCL);
                    fileValue.setSubjectId(eventId);
                    fieldValueList.add(fileValue);
                }
            }
        }
        if (!CollectionUtils.isEmpty(eventList)) {
            this.bachSave(eventList);
        }
        if (!CollectionUtils.isEmpty(fieldValueList)) {
            formGroupFieldValueService.batchSave(fieldValueList, tokenUser);
        }
    }

    @Override
    public String export(TreatmentDisposeEventExportQuery query, TokenUser tokenUser) {
        ParamException.notNull(query.getTemplateId(), "未选择模板");
        ParamException.notEmpty(query.getEventIdList(), "未选择事件");
        // 查询模板
        TreatmentDisposeTemplateDO template = treatmentDisposeTemplateService
                .selectDOById(query.getTemplateId(), tokenUser.getSiteId());
        ParamException.notNull(template, "模板不存在或已被删除");
        // 查询模板下所有表单
        List<FormGroupVO> formGroupList = formGroupService
                .selectBySubjectIdAndFormType(template.getId(), FormGroupModuleCode.DYCL, null, tokenUser);
        List<Long> formGroupIdList = formGroupList.stream().map(FormGroupVO::getId).collect(Collectors.toList());
        FormGroupFieldQuery fieldQuery = new FormGroupFieldQuery();
        fieldQuery.setSubjectIdList(formGroupIdList);
        List<List<String>> headList = new ArrayList<>();
        List<List<String>> dataList = new ArrayList<>();
        List<TreatmentDisposeEventDO> eventList = this.selectByIdList(query.getEventIdList(), tokenUser);
        ParamException.notEmpty(eventList, "导出数据为空");
        Map<String, TreatmentDisposeEventDO> eventMap = eventList.stream()
                .collect(Collectors.toMap(TreatmentDisposeEventDO::getId, v -> v));
        List<String> selectHead = new ArrayList<>();
        selectHead.add("接单时间");
        selectHead.add("接单客服");
        selectHead.add("所属用工单位");
        for (FormGroupVO formGroup : formGroupList) {
            // 查询这个表单的所有字段
            List<FormGroupFieldDO> fieldList = formGroupFieldService
                    .selectBySubjectIdList(Collections.singletonList(formGroup.getId() + ""), "site");
            // 过滤文件选择器
            fieldList = fieldList.stream().filter(field -> field.getFieldType() != 7).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(fieldList)) {
                selectHead.addAll(fieldList.stream().map(FormGroupFieldDO::getFieldName).collect(Collectors.toList()));
            }
        }
        // 先组装表头和数据
        for (String head : selectHead) {
            List<String> oneHead = new ArrayList<>();
            oneHead.add(head);
            headList.add(oneHead);
        }
        for (String eventId : query.getEventIdList()) {
            TreatmentDisposeEventDO event = eventMap.get(eventId);
            if (!ObjectUtils.isEmpty(event)) {
                List<String> oneData = new ArrayList<>();
                fieldQuery.setEventId(eventId);
                // 查询事件下的所有字段
                List<FormGroupFieldVO> formGroupFieldList = formGroupFieldService
                        .selectFieldAddContentByQuery(fieldQuery, tokenUser);
                Map<String, FormGroupFieldVO> fieldMap = formGroupFieldList.stream()
                        .collect(Collectors.toMap(FormGroupFieldVO::getFieldName, v -> v));
                for (String head : selectHead) {
                    if ("接单时间".equals(head)) {
                        oneData.add(DateKit8.format2Date(event.getTakeOrdersDate()));
                        continue;
                    }
                    if ("接单客服".equals(head)) {
                        oneData.add(event.getTakeOrdersUserName());
                        continue;
                    }
                    if ("所属用工单位".equals(head)) {
                        oneData.add(event.getCompanyName());
                        continue;
                    }
                    FormGroupFieldVO formGroupField = fieldMap.get(head);
                    if (ObjectUtils.isEmpty(formGroupField)) {
                        oneData.add("");
                    } else {
                        String content = formGroupField.getContent();
                        if (StringUtil.isEmpty(content)) {
                            oneData.add("");
                            continue;
                        }
                        if (FieldType.REGION.getValue().equals(formGroupField.getFieldType()) ||
                                FieldType.REGION_TWO.getValue().equals(formGroupField.getFieldType()) ||
                                FieldType.DETAILED_ADDRESS.getValue().equals(formGroupField.getFieldType())) {
                            //如果是地区类型需要做特殊处理  2_安徽,38_池州,422_石台县  改成  安徽-池州-石台县
                            StringBuilder areaFormat = new StringBuilder();
                            String[] splitContent = content.split(",");
                            for (int i = 0; i < splitContent.length; i++) {
                                areaFormat.append(splitContent[i].split("_")[1]);
                                if (i != splitContent.length - 1) {
                                    areaFormat.append("-");
                                }
                            }
                            content = areaFormat.toString();
                        }
                        oneData.add(content);
                    }
                }
                dataList.add(oneData);
            }
        }
        return ExcelKit.exportExcelNotTemplate("事件导出模板", dataList, headList, "事件导出");
    }

    @Override
    public List<TreatmentDisposeEventVO> selectEventByEmpId(String empId, TokenUser tokenUser) {
        EmpInfoDO empInfo = empInfoService.selectById(empId);
        Example example = new Example(TreatmentDisposeEventDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        if (StringUtil.isEmpty(empInfo.getIdCard())) {
            example.and().andEqualTo("empId", empInfo.getId());
        } else {
            example.and().andEqualTo("empIdCard", empInfo.getIdCard());
        }
        List<TreatmentDisposeEventDO> eventList = treatmentDisposeEventDAO.selectByExample(example);
        List<TreatmentDisposeEventVO> result = new ArrayList<>();
        for (TreatmentDisposeEventDO event : eventList) {
            result.add(this.selectEventInfoById(event.getId(), tokenUser));
        }
        return result;
    }

    @Override
    public List<TreatmentDisposeEventDO> findNotFinishedEventByEmpIdList(List<String> empIdList, TokenUser tokenUser) {
        Example example = new Example(TreatmentDisposeEventDO.class);
        example.and()
                .andIn("empId", empIdList)
                .andEqualTo("valid", true)
                .andEqualTo("isFinish", false)
                .andEqualTo("siteId", tokenUser.getSiteId());
        return treatmentDisposeEventDAO.selectByExample(example);
    }

    @Override
    public void bachSave(List<TreatmentDisposeEventDO> eventList) {
        treatmentDisposeEventDAO.insertListAndSetId(eventList);
    }

    @Override
    public HeaderFieldsVO getEventExportHead(HeaderFieldsQuery headerQuery, TokenUser tokenUser) {
        HeaderFieldsVO headFields = adminProviderService.getHead(headerQuery, tokenUser);
        // 如果表头是空初始化一组
        if (ObjectUtils.isEmpty(headFields)) {
            // 查询模板下的所有字段
            List<FormGroupFieldDO> formGroupFieldList = treatmentDisposeTemplateService
                    .selectFieldByTemplateId(headerQuery.getSubjectId(), tokenUser);
            // 接单时间 接单客服 所属用工单位 这三个没有在模板中是拼接上去的
            List<String> splicingHead = Arrays.asList("接单时间", "接单客服", "所属用工单位");
            if (!CollectionUtils.isEmpty(formGroupFieldList)) {
                List<String> fieldNameList = formGroupFieldList.stream()
                        .map(FormGroupFieldDO::getFieldName).collect(Collectors.toList());
                splicingHead.addAll(fieldNameList);
            }
            int sort = 1;
            List<HeaderFieldsAddDTO> insertHeadList = new ArrayList<>();
            for (String head : splicingHead) {
                HeaderFieldsAddDTO headerFieldsAdd = new HeaderFieldsAddDTO();
                headerFieldsAdd.setSubjectType("site");
                // 所有待遇处理全部是非固定
                headerFieldsAdd.setIsFix(false);
                headerFieldsAdd.setSubjectId(headerQuery.getSubjectId());
                headerFieldsAdd.setModuleCode(FormGroupModuleCode.DYCL);
                headerFieldsAdd.setModuleType("待遇处理导出");
                headerFieldsAdd.setIsOpen(true);
                headerFieldsAdd.setSort(sort++);
                headerFieldsAdd.setIsEdit(true);
                headerFieldsAdd.setFieldName(head);
                insertHeadList.add(headerFieldsAdd);
            }
            if (!CollectionUtils.isEmpty(insertHeadList)) {
                adminProviderService.bachSaveHeaderFields(insertHeadList, tokenUser);
            }
        }
        // 然后再查一遍
        return adminProviderService.getHead(headerQuery, tokenUser);
    }

    @Override
    public List<TreatmentDisposeEventDO> selectByIdList(List<String> eventIdList, TokenUser tokenUser) {
        Example example = new Example(TreatmentDisposeEventDO.class);
        example.and()
                .andIn("id", eventIdList)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        return treatmentDisposeEventDAO.selectByExample(example);
    }

    @Override
    public List<TreatmentDisposeEventDO> selectEventByTemplateId(String templateId, TokenUser tokenUser) {
        Example example = new Example(TreatmentDisposeEventDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("templateId", templateId)
                .andEqualTo("siteId", tokenUser.getSiteId());
        return treatmentDisposeEventDAO.selectByExample(example);
    }

    @Override
    @Async
    public void addFieldAsyncUpdateEvent(String templateId, List<FormGroupFieldVO> fieldList, TokenUser tokenUser) {
        List<TreatmentDisposeEventDO> eventList = this.selectEventByTemplateId(templateId, tokenUser);
        if (CollectionUtils.isEmpty(eventList)) {
            return;
        }
        List<Long> fieldIdList = fieldList.stream().map(FormGroupFieldVO::getId).collect(Collectors.toList());
        List<FormGroupFieldValueAddDTO> addFieldValueList = new ArrayList<>();
        for (TreatmentDisposeEventDO event : eventList) {
            for (Long fieldId : fieldIdList) {
                FormGroupFieldValueAddDTO fieldValue = new FormGroupFieldValueAddDTO();
                fieldValue.setFieldId(fieldId);
                fieldValue.setSubjectId(event.getId());
                fieldValue.setSubjectType(FormGroupModuleCode.DYCL);
                addFieldValueList.add(fieldValue);
            }
        }
        if (!CollectionUtils.isEmpty(addFieldValueList)) {
            formGroupFieldValueService.batchSave(addFieldValueList, tokenUser);
        }
    }

    /**
     * 根据查询参数，构建example
     *
     * @param treatmentDisposeEventQuery 查询参数
     * @param siteId                     所属站点id
     * @return example
     */
    private Example buildExample(TreatmentDisposeEventQuery treatmentDisposeEventQuery, String siteId) {
        Example example = new Example(TreatmentDisposeEventDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (!StringUtil.isEmpty(treatmentDisposeEventQuery.getNameOrIdCard())) {
            example.and()
                    .orLike("empName", "%" + treatmentDisposeEventQuery.getNameOrIdCard() + "%")
                    .orLike("empIdCard", "%" + treatmentDisposeEventQuery.getNameOrIdCard() + "%");
        }
        if (!StringUtil.isEmpty(treatmentDisposeEventQuery.getTemplateId())) {
            example.and().andEqualTo("templateId", treatmentDisposeEventQuery.getTemplateId());
        }
        if (!StringUtil.isEmpty(treatmentDisposeEventQuery.getEventType())) {
            example.and().andEqualTo("eventType", treatmentDisposeEventQuery.getEventType());
        }
        if (!StringUtil.isEmpty(treatmentDisposeEventQuery.getCurrentWorkflow())) {
            example.and().andLike("currentWorkflow",
                    "%" + treatmentDisposeEventQuery.getCurrentWorkflow() + "%");
        }
        if (!ObjectUtils.isEmpty(treatmentDisposeEventQuery.getTakeOrdersBeginDate())) {
            example.and().andGreaterThanOrEqualTo("takeOrdersDate", treatmentDisposeEventQuery.getTakeOrdersBeginDate());
        }
        if (!ObjectUtils.isEmpty(treatmentDisposeEventQuery.getTakeOrdersEndDate())) {
            example.and().andLessThanOrEqualTo("takeOrdersDate", treatmentDisposeEventQuery.getTakeOrdersEndDate());
        }
        if (!StringUtil.isEmpty(treatmentDisposeEventQuery.getCompanyName())) {
            example.and().andLike("companyName", "%" + treatmentDisposeEventQuery.getCompanyName() + "%");
        }
        if (!StringUtil.isEmpty(treatmentDisposeEventQuery.getTakeOrdersUserName())) {
            example.and().andLike("takeOrdersUserName",
                    "%" + treatmentDisposeEventQuery.getTakeOrdersUserName() + "%");
        }
        if (!StringUtil.isEmpty(treatmentDisposeEventQuery.getWorkCity())) {
            example.and().andLike("workCity", "%" + treatmentDisposeEventQuery.getWorkCity() + "%");
        }
        if (!ObjectUtils.isEmpty(treatmentDisposeEventQuery.getIsFinish())) {
            example.and().andEqualTo("isFinish", treatmentDisposeEventQuery.getIsFinish());
        }
        return example;
    }
}




